import { Directive, ElementRef, Input, Renderer } from '@angular/core';
@Directive({
  selector: '[imageLoader]'
})
export class ImageLoaderDirective {
  @Input() errorPath: string;

  //TO USE 
  //<img style="height: 100px;width:100px;" errpath='..../x.jpg' src="http://img.netbian.com/file/2017/0404/50536abbe2003929424dc55f10a288e4.jpg" imageLoader />

  constructor(private el: ElementRef,
    private renderer: Renderer) {
    // this.el = el.nativeElement.style;
    el.nativeElement.style.backgroundImage = "url(assets/imgs/imgload/spinner.gif)";
    el.nativeElement.style.backgroundSize = "cover";
  }
  //http://stackoverflow.com/questions/38536265/display-a-loading-icon-while-images-loads 改造

  ngOnInit() {
    setTimeout(() => {
         // let self = this;
        let image = new Image();
        image.addEventListener('load', () => {
          //加载成功
          this.el.nativeElement.style.backgroundImage = "";
        });
        image.addEventListener('error', () => {
          //加载失败
          if(!this.errorPath){
            this.el.nativeElement.src = "assets/imgs/imgload/img-error.jpg"
          }else{
            this.el.nativeElement.src = this.errorPath;
          }
        });
    }, 0);

    setTimeout(() => { 
      let _type = this.el.nativeElement.src
       _type=_type.toUpperCase();  
       //此处可用正则或者其他更好的方式
      if(_type.indexOf("JPEG")=='-1' && _type.indexOf("PNG")=='-1' && _type.indexOf("JPG")=='-1' && _type.indexOf("GIF")=='-1') {
        this.renderer.setElementAttribute(this.el.nativeElement, 'src', 'assets/imgs/imgload/img-error.jpg');
        // this.el.nativeElement.style.src = "assets/img/img-error.jpg";
      }
    }, 0);

  }


}